//! PartyRelationship实体相关的数据结构

use chrono::{DateTime, Utc, TimeZone};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// PartyRelationship实体 - 参与方关系
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartyRelationship {
    pub party_id_from: String,
    pub party_id_to: String,
    pub role_type_id_from: String,
    pub role_type_id_to: String,
    pub from_date: DateTime<Utc>,
    pub thru_date: Option<DateTime<Utc>>,
    pub status_id: Option<String>,
    pub relationship_name: Option<String>,
    pub security_group_id: Option<String>,
    pub priority_type_id: Option<String>,
    pub party_relationship_type_id: Option<String>,
    pub permissions_enum_id: Option<String>,
    pub position_title: Option<String>,
    pub comments: Option<String>,
}

/// PartyRelationshipType实体 - 参与方关系类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartyRelationshipType {
    pub party_relationship_type_id: String,
    pub parent_type_id: Option<String>,
    pub has_table: Option<bool>,
    pub party_relationship_name: Option<String>,
    pub description: Option<String>,
    pub role_type_id_valid_from: Option<String>,
    pub role_type_id_valid_to: Option<String>,
}

/// 组织成员关系的便捷结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrganizationMember {
    pub organization_party_id: String,
    pub member_party_id: String,
    pub member_role_type_id: String,
    pub from_date: DateTime<Utc>,
    pub thru_date: Option<DateTime<Utc>>,
    pub position_title: Option<String>,
    pub status_id: Option<String>,
}

/// 客户关系的便捷结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerRelationship {
    pub customer_party_id: String,
    pub sales_rep_party_id: String,
    pub from_date: DateTime<Utc>,
    pub thru_date: Option<DateTime<Utc>>,
    pub relationship_type: String, // CUSTOMER, PROSPECT, etc.
    pub status_id: Option<String>,
}

impl PartyRelationship {
    /// 创建新的PartyRelationship实例
    pub fn new(
        party_id_from: String,
        party_id_to: String,
        role_type_id_from: String,
        role_type_id_to: String,
    ) -> Self {
        Self {
            party_id_from,
            party_id_to,
            role_type_id_from,
            role_type_id_to,
            from_date: Utc::now(),
            thru_date: None,
            status_id: Some("PARTY_ENABLED".to_string()),
            relationship_name: None,
            security_group_id: None,
            priority_type_id: None,
            party_relationship_type_id: None,
            permissions_enum_id: None,
            position_title: None,
            comments: None,
        }
    }

    /// 创建组织成员关系
    pub fn create_organization_member(
        organization_id: String,
        member_id: String,
        role_type: String,
        position_title: Option<String>,
    ) -> Self {
        let mut relationship = Self::new(
            organization_id,
            member_id,
            "INTERNAL_ORGANIZATIO".to_string(),
            role_type,
        );
        relationship.party_relationship_type_id = Some("EMPLOYMENT".to_string());
        relationship.position_title = position_title;
        relationship
    }

    /// 创建客户关系
    pub fn create_customer_relationship(
        sales_rep_id: String,
        customer_id: String,
        relationship_type: String,
    ) -> Self {
        let mut relationship = Self::new(
            sales_rep_id,
            customer_id,
            "SALES_REP".to_string(),
            "CUSTOMER".to_string(),
        );
        relationship.party_relationship_type_id = Some(relationship_type);
        relationship
    }

    /// 检查关系是否有效（未过期）
    pub fn is_active(&self) -> bool {
        match self.thru_date {
            Some(thru_date) => Utc::now() <= thru_date,
            None => true,
        }
    }

    /// 结束关系
    pub fn end_relationship(&mut self) {
        self.thru_date = Some(Utc::now());
        self.status_id = Some("PARTY_DISABLED".to_string());
    }

    /// 转换为HashMap用于数据库操作
    pub fn to_data_row(&self) -> HashMap<String, String> {
        let mut data = HashMap::new();
        data.insert("partyIdFrom".to_string(), self.party_id_from.clone());
        data.insert("partyIdTo".to_string(), self.party_id_to.clone());
        data.insert("roleTypeIdFrom".to_string(), self.role_type_id_from.clone());
        data.insert("roleTypeIdTo".to_string(), self.role_type_id_to.clone());
        data.insert("fromDate".to_string(), self.from_date.to_rfc3339());
        
        if let Some(thru_date) = self.thru_date {
            data.insert("thruDate".to_string(), thru_date.to_rfc3339());
        }
        if let Some(ref status_id) = self.status_id {
            data.insert("statusId".to_string(), status_id.clone());
        }
        if let Some(ref relationship_name) = self.relationship_name {
            data.insert("relationshipName".to_string(), relationship_name.clone());
        }
        if let Some(ref security_group_id) = self.security_group_id {
            data.insert("securityGroupId".to_string(), security_group_id.clone());
        }
        if let Some(ref priority_type_id) = self.priority_type_id {
            data.insert("priorityTypeId".to_string(), priority_type_id.clone());
        }
        if let Some(ref party_relationship_type_id) = self.party_relationship_type_id {
            data.insert("partyRelationshipTypeId".to_string(), party_relationship_type_id.clone());
        }
        if let Some(ref permissions_enum_id) = self.permissions_enum_id {
            data.insert("permissionsEnumId".to_string(), permissions_enum_id.clone());
        }
        if let Some(ref position_title) = self.position_title {
            data.insert("positionTitle".to_string(), position_title.clone());
        }
        if let Some(ref comments) = self.comments {
            data.insert("comments".to_string(), comments.clone());
        }
        
        data
    }

    /// 从HashMap创建PartyRelationship实例
    pub fn from_data_row(data: &HashMap<String, String>) -> crate::Result<Self> {
        let party_id_from = data.get("partyIdFrom")
            .ok_or_else(|| Box::new(crate::PartyModError::InvalidData("Missing partyIdFrom".to_string())))?
            .clone();
        let party_id_to = data.get("partyIdTo")
            .ok_or_else(|| Box::new(crate::PartyModError::InvalidData("Missing partyIdTo".to_string())))?
            .clone();
        let role_type_id_from = data.get("roleTypeIdFrom")
            .ok_or_else(|| Box::new(crate::PartyModError::InvalidData("Missing roleTypeIdFrom".to_string())))?
            .clone();
        let role_type_id_to = data.get("roleTypeIdTo")
            .ok_or_else(|| Box::new(crate::PartyModError::InvalidData("Missing roleTypeIdTo".to_string())))?
            .clone();
        let from_date = data.get("fromDate")
            .map(|s| {
                // 如果是空字符串，使用当前时间
                if s.trim().is_empty() {
                    Ok(Utc::now())
                } else {
                    // 尝试多种日期格式
                    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
                        Ok(dt.with_timezone(&Utc))
                    } else if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
                        Ok(Utc.from_utc_datetime(&dt))
                    } else if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
                        Ok(Utc.from_utc_datetime(&dt))
                    } else {
                        Err(Box::new(crate::PartyModError::InvalidData(format!("Invalid fromDate format: {}", s))))
                    }
                }
            })
            .unwrap_or_else(|| Ok(Utc::now()))?;

        Ok(Self {
            party_id_from,
            party_id_to,
            role_type_id_from,
            role_type_id_to,
            from_date,
            thru_date: data.get("thruDate")
                .and_then(|s| {
                    if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
                        Some(dt.with_timezone(&Utc))
                    } else if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
                        Some(Utc.from_utc_datetime(&dt))
                    } else if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
                        Some(Utc.from_utc_datetime(&dt))
                    } else {
                        None
                    }
                }),
            status_id: data.get("statusId").cloned(),
            relationship_name: data.get("relationshipName").cloned(),
            security_group_id: data.get("securityGroupId").cloned(),
            priority_type_id: data.get("priorityTypeId").cloned(),
            party_relationship_type_id: data.get("partyRelationshipTypeId").cloned(),
            permissions_enum_id: data.get("permissionsEnumId").cloned(),
            position_title: data.get("positionTitle").cloned(),
            comments: data.get("comments").cloned(),
        })
    }
}

impl OrganizationMember {
    /// 从PartyRelationship创建OrganizationMember
    pub fn from_party_relationship(relationship: &PartyRelationship) -> Self {
        Self {
            organization_party_id: relationship.party_id_from.clone(),
            member_party_id: relationship.party_id_to.clone(),
            member_role_type_id: relationship.role_type_id_to.clone(),
            from_date: relationship.from_date,
            thru_date: relationship.thru_date,
            position_title: relationship.position_title.clone(),
            status_id: relationship.status_id.clone(),
        }
    }
}

impl CustomerRelationship {
    /// 从PartyRelationship创建CustomerRelationship
    pub fn from_party_relationship(relationship: &PartyRelationship) -> Self {
        Self {
            customer_party_id: relationship.party_id_to.clone(),
            sales_rep_party_id: relationship.party_id_from.clone(),
            from_date: relationship.from_date,
            thru_date: relationship.thru_date,
            relationship_type: relationship.party_relationship_type_id
                .clone()
                .unwrap_or_else(|| "CUSTOMER".to_string()),
            status_id: relationship.status_id.clone(),
        }
    }
}